package com.xuecheng.filesyetem.service;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.xuecheng.filesyetem.dao.FileSystemRepository;
import com.xuecheng.framework.domain.filesystem.FileSystem;
import com.xuecheng.framework.domain.filesystem.response.FileSystemCode;
import com.xuecheng.framework.domain.filesystem.response.UploadFileResult;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;

@Service
public class FileSystemService {
    
    //读取配置文件中的信息
    @Value("${xuecheng.fastdfs.tracker_servers}")
    String tracker_servers;
    
    @Value("${xuecheng.fastdfs.connect_timeout_in_seconds}")
    int connect_timeout_in_seconds;
    
    @Value("${xuecheng.fastdfs.network_timeout_in_seconds}")
    int network_timeout_in_seconds;
    
    
    @Value("${xuecheng.fastdfs.charset}")
    String charset;
    
    
    @Autowired
    FileSystemRepository fileSystemRepository;
    
    //上传文件
    public UploadFileResult upload(MultipartFile multipartFile,String fileTag,
            String businessKey,String metadata) {
        if(multipartFile == null) {
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_FILEISNULL);
        }
        //将文件上传至fastDFS，获取一个文件ID
        String fileId = fds_upload(multipartFile);
        if(StringUtils.isEmpty(fileId)) {
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_SERVERFAIL);
        }
        //将文件ID和其他信息存到mongodb中
        FileSystem fileSystem = new FileSystem();
        fileSystem.setFileId(fileId);
        fileSystem.setFilePath(fileId);
        fileSystem.setFiletag(fileTag);
        fileSystem.setBusinesskey(businessKey);
        fileSystem.setFileName(multipartFile.getOriginalFilename());
        fileSystem.setFileType(multipartFile.getContentType());
        if(StringUtils.isNotEmpty(metadata)) {
            //设置元数据信息，需要将json转map
            try {
                Map map = JSON.parseObject(metadata,Map.class);
                fileSystem.setMetadata(map);
            } catch (Exception e) {
               e.printStackTrace();
            }
        }
        //保存信息到数据库
        fileSystemRepository.save(fileSystem);
        return new UploadFileResult(CommonCode.SUCCESS, fileSystem);
    }
    
    //定义一个私有方法，上传文件
    private String fds_upload(MultipartFile multipartFile) {
        try {
            //初始化fastDFS环境
            initFastDfsConfig();
            //创建TrackerClient
            TrackerClient trackerClient = new TrackerClient();
            //获取TrackerServer
            TrackerServer trackerServer = trackerClient.getConnection();
            //获取StorageServer
            StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
            //获取StorageClient
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);
            //得到文件字节
            byte []bys = multipartFile.getBytes();
            //获取文件的原始名称
            String fileName = multipartFile.getOriginalFilename();
            //获取文件扩展名
            String ext = fileName.substring(fileName.lastIndexOf(".")+1);
            //上传文件，返回文件ID
            String fileId = storageClient1.upload_file1(bys, ext, null);
            return fileId;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    //定义一个私有方法，初始化fastDFS环境
    private void initFastDfsConfig() {
        try {
            //初始化tracker
            ClientGlobal.initByTrackers(tracker_servers);
            ClientGlobal.setG_connect_timeout(connect_timeout_in_seconds);
            ClientGlobal.setG_network_timeout(network_timeout_in_seconds);
            ClientGlobal.setG_charset(charset);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionCast.cast(FileSystemCode.FS_INITFASTDFS_ISERROR);
        }
    }

}
